<?php


namespace app\api\controller;

use app\common\model\User;
use app\common\server\UrlServer;
use app\api\server\UserServer;
use app\common\validate\UserValidate;
use Exception;
use think\Request;
use think\response\Json;
use tools\Crypt;
use tools\WXBizDataCrypt;
use tools\DySms;
use think\facade\Cache;
use think\facade\Env;
use think\Db;

class AuthController extends ApiBase
{
    protected $authExcept = [
        'wxlogin','wxlogin_dl'
    ];

    /**
     * 检查用户微信小程序是否注册
     * @param Request $request
     * @param User $model
     * @param UserValidate $validate
     * @return Json|void
     */
    public function wxlogin_dl(Request $request,User $fumodel)
    {
        $param = $request->param();
        $code =$param['code']??'';
        $APPID =config('wechat.app_id');
        $APPSECRET=config('wechat.secret');
        $encryptedData='';
        $iv='';
        $response = $this->get_openid($code,$encryptedData,$iv,$APPID,$APPSECRET);
        if (!isset($response['openid'])) {
            return client_error('授权失败');
        }
        $user_id = Db::name('user_auth au')
            ->join('user u', 'au.user_id=u.id')
            ->where(['u.delete_time' => 0])
            ->where(function ($query) use ($response) {
                $query->whereOr(['au.openid' => $response['openid']]);
                    if(isset($response['unionid']) && !empty($response['unionid'])){
                      $query->whereOr(['au.unionid' => $response['unionid']]);
                    }
            })
            ->value('user_id');
        $where['id'] = array('EQ',$user_id);
        $userinfo = $fumodel->field('id,avatar,nickname')->where($where)->find();
        if(!$userinfo){
            return client_error('授权失败');
        }
        $data['avatar']=$userinfo['avatar'];
        $data['avatar_logo']=UrlServer::setFileUrl($userinfo['avatar']);
        $data['nickName']=$userinfo['nickname'];
        return success($data);
    }

    /**
     * 微信小程序登录并发放token
     * @param Request $request
     * @param User $model
     * @param UserValidate $validate
     * @return Json|void
     */
    public function wxlogin(Request $request,User $fumodel)
    {
        $param = $request->param();
       
        $avatar =$param['avatar']??'';
        $nickname =$param['nickname']??'';
        $code =$param['code']??'';
        $encryptedData =$param['encryptedData']??'';
        $iv =$param['iv']??'';
        if(!$avatar || !$nickname || !$code){
            return error('参数不足');
        }
        
        $APPID =config('wechat.app_id');
        
        $APPSECRET=config('wechat.secret');
        
        $response = $this->get_openid($code,$encryptedData,$iv,$APPID,$APPSECRET);
        
        if (!isset($response['openid'])) {
            return client_error('授权失败');
        }
                
        $response['avatar']=$avatar;
        $response['nickname']=$nickname;
        $user_id = Db::name('user_auth au')
            ->join('user u', 'au.user_id=u.id')
            ->where(['u.delete_time' => 0])
            ->where(function ($query) use ($response) {
                $query->whereOr(['au.openid' => $response['openid']]);
                    if(isset($response['unionid']) && !empty($response['unionid'])){
                      $query->whereOr(['au.unionid' => $response['unionid']]);
                    }
            })
            ->value('user_id');
        // 启动事务
        $fumodel->startTrans();
        try {
            if (empty($user_id)) {
                $user_info = UserServer::createUser($response,1);
            } else {
                $user_info = UserServer::updateUser($response,1, $user_id);
            }
            $fumodel->commit();
        } catch (Exception $e) {
            $fumodel->rollback();
            return client_error($e->getMessage());
        }
        
        $token = $this->getToken($user_info['id']);
        //返回数据
        return success(['token' => $token,'uid'=>$user_info['id'],'user_info'=>$user_info], '注册成功');
    }
    //获取用户临时code 用来去获取openid
    public function get_openid($code,$encryptedData,$iv,$APPID,$APPSECRET)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $APPID. '&secret=' . $APPSECRET. '&js_code=' . $code . '&grant_type=authorization_code';
        $val = curl_request($url);
        $user_info = json_decode($val,true);
        // return $user_info;
        if($encryptedData && $iv){
            $encryptedData=urldecode($encryptedData);
            $iv = urldecode($iv);
            $pc = new WXBizDataCrypt($APPID,$user_info['session_key']);
            $errCode = $pc->decryptData($encryptedData,$iv,$data);
            $data1 = json_decode($data, true);
           
            if(isset($data1['purePhoneNumber']) && !empty($data1['purePhoneNumber'])){
                $user_info['tel']=$data1['purePhoneNumber'];
            }
            // $user_info['tel']=$data1['purePhoneNumber'];
            
        }
        
        
        return $user_info;
    }
}